<template>
  <div class="login">
    <van-nav-bar title="登录" left-arrow @click-left="onClickLeft" />
    <section class="van-section">
      <section class="van-block">
        <h2 class="van-title">验证手机号码</h2>
      </section>
    </section>
    <van-cell-group>
      <phone-and-code ref="fields"></phone-and-code>
    </van-cell-group>
    <section class="van-section">
      <section class="van-block">
        <van-button 
          size="large" 
          :loading="appLoading"
          loading-text="加载中"
          color="linear-gradient(to right, #4bb0ff, #6149f6)"
          @click="submit"
        >马上登录</van-button>
      </section>
    </section>
  </div>
</template>

<script>
  import { NavBar, CellGroup, Field, Button } from 'vant';
  import { default as PhoneAndCode } from '../../components/PhoneAndCode';
  import { mapState, mapMutations } from 'vuex';
  import { mixins } from '../../common/mixins';

  export default {
    name: 'login',
    components: {
      [NavBar.name]: NavBar,
      [CellGroup.name]: CellGroup,
      [Field.name]: Field,
      [Button.name]: Button,
      PhoneAndCode
    },
    mixins: [mixins],
    data () {
      return {
        redirectPath: this.$route.query.redirect ? this.$route.query.redirect : ''
      }
    },
    computed:{
      ...mapState ([
        'appLoading', // 将 this.appLoading 映射为 this.$store.state.appLoading
      ]),
    },
    created(){
    },
    methods:{
      ...mapMutations ([ 
        'updateToken', // 将 this.updateToken(value) 映射为 this.$store.commit('updateToken', value)
      ]),
      ...mapMutations ('user', [ // 带命名空间的方法
        'updateUserInfo'
      ]),
      changeFocus (val) {
        if(val == null) {document.getElementById('loginBtn').focus();
        this.submit();}
        else document.getElementById(val).getElementsByTagName('input')[0].focus();
      },
      submit () {
        let checkResult = this.$refs.fields.checkSubmit();
        if (checkResult.result){
          this.$api.user.loginVerify(checkResult.reqParams, (res) => {
            let {msg, code, data} = res;
            this.updateToken(data.token);
            this.updateUserInfo({phone: data.phone});
            if(this.redirectPath == '')
              this.$router.push({path: '/'});
            else
              this.$router.push({path: this.redirectPath});
          })
        }
      },
    }
  }
</script>

<style lang="scss">
  .login {
  }
</style>
